﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics;
using System.Linq;
using System.Threading.Tasks;
using System.Windows.Forms;
using SiChuan.FormsApp.AppCode.Exceptions;
using SiChuan.FormsApp.AppCode.Helpers;

namespace SiChuan.FormsApp {
    internal static class Program {

        public static ApplicationContext context;
        /// <summary>
        /// 应用程序的主入口点。
        /// </summary>
        [STAThread]
        static void Main() {
            try {

                //处理未捕获的异常
                Application.SetUnhandledExceptionMode(UnhandledExceptionMode.CatchException);
                //处理UI线程异常
                Application.ThreadException += Application_ThreadException;
                //处理非UI线程异常
                AppDomain.CurrentDomain.UnhandledException += CurrentDomain_UnhandledException;

                var aProcessName = Process.GetCurrentProcess().ProcessName;
                if ((Process.GetProcessesByName(aProcessName)).GetUpperBound(0) > 0) {
                    MessageBox.Show(@"系统已经在运行中...", @"提示", MessageBoxButtons.OK, MessageBoxIcon.Asterisk);
                } else {
                    Application.EnableVisualStyles();
                    Application.SetCompatibleTextRenderingDefault(false);
                    context = new ApplicationContext();
                    Application.Idle += Application_Idle; //注册程序运行空闲去执行主程序窗体相应初始化代码
                    Application.Run(context);
                }

                //Application.EnableVisualStyles();
                //Application.SetCompatibleTextRenderingDefault(false);
                //Application.Run(new Form1());
            } catch (WarnException ex) {
                MainForm.KEY_LOADING = false;
                NlogHelper.Warn(ex.Message);
            } catch (Exception ex) {
                MainForm.KEY_LOADING = false;
                //MainForm.applock = false;
                string str = "";
                string strDateInfo = "出现应用程序未处理的异常：" + DateTime.Now.ToString() + "\r\n";
                if (ex != null) {
                    str = string.Format(strDateInfo + "异常类型：{0}\r\n异常消息：{1}\r\n异常信息：{2}\r\n",
                       ex.GetType().Name, ex.Message, ex.StackTrace);
                } else {
                    str = string.Format("应用程序线程错误:{0}", ex);
                }
                NlogHelper.Error(str);
                MessageBox.Show("发生未知错误，如多次出现请及时联系作者！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }

        }

        private static void Application_Idle(object sender, EventArgs e) {
            Application.Idle -= Application_Idle;
            if (context.MainForm == null) {
                Form form = new MainForm();
                context.MainForm = form;
                form.Show();
            }
        }

        static void Application_ThreadException(object sender, System.Threading.ThreadExceptionEventArgs e) {
            if (e.Exception is WarnException) {
                var ex = e.Exception as WarnException;
                MainForm.KEY_LOADING = false;
                NlogHelper.Warn(ex.Message);
                return;
            }
            NlogHelper.Error(e.Exception);
            MessageBox.Show("发生未知错误，如多次出现请及时联系作者！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Error);
            MainForm.KEY_LOADING = false;
        }

        static void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e) {
            //MainForm.applock = false;
            string str = "";
            if (e.ExceptionObject is WarnException) {
                var ex = e.ExceptionObject as WarnException;
                MainForm.KEY_LOADING = false;
                NlogHelper.Warn(ex.Message);
                return;
            }
            Exception error = e.ExceptionObject as Exception;
            MainForm.KEY_LOADING = false;
            string strDateInfo = "出现应用程序未处理的异常：" + DateTime.Now.ToString() + "\r\n";
            if (error != null) {
                str = string.Format(strDateInfo + "Application UnhandledException:{0};\n\r堆栈信息:{1}", error.Message, error.StackTrace);
            } else {
                str = string.Format("Application UnhandledError:{0}", e);
            }
            NlogHelper.Error(str);
            //frmBug f = new frmBug(str);//友好提示界面
            //f.ShowDialog();
            MessageBox.Show("发生未知错误，如多次出现请及时联系作者！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Error);
        }
    }
}
